from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.api import deps
from app.schemas import customer as schemas
from app.database.models.erp import CustomerTelNo, CustomerProfile
from app.database.models.base import User

router = APIRouter()

@router.get("/{customer_id}/tel-nos", response_model=List[schemas.CustomerTelNo])
def get_customer_tel_nos(
    customer_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取客户的电话号码列表"""
    try:
        # 先检查客户是否存在
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_id).first()
        if not customer:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 获取电话号码列表
        tel_nos = db.query(CustomerTelNo)\
            .filter(CustomerTelNo.customer_profile_id == customer_id)\
            .all()
        return tel_nos
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/{customer_id}/tel-nos", response_model=schemas.CustomerTelNo)
def create_customer_tel_no(
    *,
    db: Session = Depends(deps.get_db),
    customer_id: int,
    tel_no_in: schemas.CustomerTelNoCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """为客户添加新的电话号码"""
    try:
        # 先检查客户是否存在
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_id).first()
        if not customer:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 创建新的电话号码记录
        tel_no_data = tel_no_in.dict()
        tel_no_data["customer_profile_id"] = customer_id
        tel_no = CustomerTelNo(**tel_no_data)

        db.add(tel_no)
        db.commit()
        db.refresh(tel_no)
        return tel_no
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{customer_id}/tel-nos/{tel_no_id}", response_model=schemas.CustomerTelNo)
def update_customer_tel_no(
    *,
    db: Session = Depends(deps.get_db),
    customer_id: int,
    tel_no_id: int,
    tel_no_in: schemas.CustomerTelNoUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新客户的电话号码"""
    try:
        # 先检查电话号码记录是否存在
        tel_no = db.query(CustomerTelNo)\
            .filter(CustomerTelNo.ID == tel_no_id)\
            .filter(CustomerTelNo.customer_profile_id == customer_id)\
            .first()
        if not tel_no:
            raise HTTPException(status_code=404, detail="Tel no not found")

        # 检查权限
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_id).first()
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新电话号码信息
        update_data = tel_no_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(tel_no, field, value)

        db.add(tel_no)
        db.commit()
        db.refresh(tel_no)
        return tel_no
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{customer_id}/tel-nos/{tel_no_id}")
def delete_customer_tel_no(
    *,
    db: Session = Depends(deps.get_db),
    customer_id: int,
    tel_no_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除客户的电话号码"""
    try:
        # 先检查电话号码记录是否存在
        tel_no = db.query(CustomerTelNo)\
            .filter(CustomerTelNo.ID == tel_no_id)\
            .filter(CustomerTelNo.customer_profile_id == customer_id)\
            .first()
        if not tel_no:
            raise HTTPException(status_code=404, detail="Tel no not found")

        # 检查权限
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_id).first()
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        db.delete(tel_no)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 